package com.bolinfest.editor;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.docs.DocumentEntry;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.util.ServiceException;

/**
 * Servlet that handles requests to create a document in Google Docs.
 * @author bolinfest@gmail.com (Michael Bolin)
 */
public class CreateDocumentServlet extends HttpServlet {

  private static final long serialVersionUID = 1L;

  private static UserService userService = UserServiceFactory.getUserService();

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    XsrfUtil.checkNotXsrf(req);

    String title = req.getParameter("title");
    DocsService client = FeedProxy.getDocsService();

    DocumentListEntry newEntry = new DocumentEntry();
    newEntry.setTitle(new PlainTextConstruct(title));
    DocumentListEntry entry;
    try {
      entry = client.insert(new URL(
        "https://docs.google.com/feeds/default/private/full/"), newEntry);
    } catch (MalformedURLException e) {
      throw new ServletException(e);
    } catch (ServiceException e) {
      throw new ServletException(e);
    }

    // Add the newly created document to the list of the user's
    User user = userService.getCurrentUser();
    String documentId = entry.getId();
    PersistenceManager pm = PMF.get().getPersistenceManager();
    UserPreferences prefs = UserPreferences.getPrefsForUser(user, pm);
    prefs.addDocumentId(documentId);
    pm.close();

    resp.getWriter().write(documentId);
  }

}
